def permute[A](as:List[A]):List[List[A]]= {
    if(as==Nil)Nil
    else 
    if(as.length==1) List(as)
    else {
        val prevPermu=permute(as.tail)
        val result=Nil
        var x=as.head
        var xs= List[List[A]]()
        for(i <-0 to prevPermu.length-1;j<-0 to as.length-1) {
            xs=((prevPermu(i) take j):::List(x):::(prevPermu(i) drop j))::xs
        }
        return xs
    }
}
test("permute") {
    permute(Nil) should equal (Nil)
    permute(List(0)) should equal (List(List(0)))
    permute(List(0,1)) should equal (List(List(1,0),List(0,1)))
    def fact(n:Int):Int= {
        if (n==0)1 else n*fact(n-1)
    }
    val count=5
    val perms=permute(List.range(0,count))
    perms.length should equal (fact(count)) 
    perms foreach println
}
